package com.gk.panda.apis.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gk.panda.apis.log.Log;
import com.gk.panda.apis.service.OrgService;
import com.gk.panda.commons.result.Result;
import com.gk.panda.pojo.Org;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@Api(tags = "机构")
@RequestMapping("/org")
public class OrgController {

    @Autowired
    private OrgService orgService;

    @ApiOperation(value = "增加机构")
    @Log
    @PostMapping
    public Result<String> addOrg(@RequestBody Org org)  {
        org.setPersonNum(org.getPermanent()+org.getUnPermanent());
        boolean save = orgService.save(org);
        if (!save) return Result.write(201,"添加失败");
        return Result.write(200,"添加成功");
    }

    @ApiOperation(value = "修改机构")
    @Log
    @PutMapping
    public Result<String> updateOrg(@RequestBody Org org) {
        org.setPersonNum(org.getPermanent()+org.getUnPermanent());
        boolean update = orgService.updateById(org);
        if (!update) return Result.write(201,"修改失败");
        return Result.write(200,"修改成功");
    }

    @ApiOperation(value = "删除机构")
    @Log
    @DeleteMapping("/{id}")
    public Result<String> deleteOrg(@PathVariable int id) {
        int delete = orgService.deleteById(id);
        if (delete == -1) {
            return Result.write(201,"该机构下有账号关联或子机构，请清理完后再删除！");
        } else if (delete == 0) {
            return Result.write(201,"删除失败");
        } return Result.write(200,"删除成功");
    }

    @ApiOperation(value = "查询所有机构")
    @GetMapping
    public Result<Page<Org>> getOrg(@RequestParam int pageNumber, @RequestParam int pageSize, Integer orgId) {
        return Result.ok(orgService.getOrg(pageNumber,pageSize,orgId));
    }

    @ApiOperation(value = "查询所有机构(不包括管护区域GeoJson数据)")
    @GetMapping("/page")
    public Result<Page<Org>> getOrgPage(@RequestParam int pageNumber,@RequestParam int pageSize) {
        return Result.ok(orgService.getOrgPage(pageNumber,pageSize));
    }

    @ApiOperation(value = "根据id查询机构详情")
    @GetMapping("/getInfo/{id}")
    public Result<Org> getOrgById(@PathVariable("id") int id) {
        return Result.ok(orgService.getById(id));
    }

    @ApiOperation(value = "根据机构id查询下属保护站列表")
    @GetMapping("/getPuisneOrgListById")
    public Result<List<Org>> getPuisneOrgListById(Integer id) {
        return Result.ok(orgService.getPuisneOrgListById(id));
    }
}
